<template>
<div v-loading="loading">
  <el-descriptions title="基本信息" direction="vertical" :column="2" border>
    <el-descriptions-item :label="$t('bs.department')">{{temp.department_name}}</el-descriptions-item>
    <el-descriptions-item :label="$t('bs.stream')">{{temp.cost_name}}</el-descriptions-item>
    <el-descriptions-item :label="$t('bs.productionLine')">{{temp.line_name}}</el-descriptions-item>
    <el-descriptions-item :label="$t('bs.productionLine')">{{temp.line_name}}</el-descriptions-item>

    <el-descriptions-item :label="$t('bs.stationNumber')">{{temp.station_number}}</el-descriptions-item>

    <el-descriptions-item :label="$t('bs.workerNumber')">{{temp.work_position}}</el-descriptions-item>

    <el-descriptions-item :label="$t('bs.deviceName')">{{temp.station_name}}</el-descriptions-item>

    <el-descriptions-item label="设备英文名">{{temp.station_name_en}}</el-descriptions-item>

    <el-descriptions-item :label="$t('bs.supplier')">{{temp.supplier}}</el-descriptions-item>

    <el-descriptions-item :label="$t('bs.costCenter')">{{temp.cost_center}}</el-descriptions-item>

    <el-descriptions-item :label="$t('bs.productionLineCode')">{{temp.line_equipment_code}}</el-descriptions-item>


    <el-descriptions-item :label="$t('bs.equipmentDrawingName')">{{temp.equipment_drawings}}</el-descriptions-item>

    <el-descriptions-item :label="$t('bs.deviceType')">{{temp.dev_type}}</el-descriptions-item>
    <el-descriptions-item :label="$t('bs.assetNumber')">{{temp.inventory_no}}</el-descriptions-item>
  </el-descriptions>
  <el-form ref="dataForm" :model="temp" :rules="rules"   label-position="top">
    <el-divider content-position="left">工艺信息</el-divider>
  <el-row :gutter="24">
    <el-col :span="24">
      <el-form-item :label="$t('bs.processType')" prop="technology_type" label-position="top">
        <el-select v-model="temp.technology_type" :disabled="true">
          <el-option
              v-for="(item,k) in technology_type_option"
              :key="k"
              :label="item.technology_name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-col>

    <el-col :span="24">
      <div class="el-transfer-panel" style="width: 100%">
        <div class="el-transfer-panel__header">
          工艺细分
        </div>
        <div class="el-transfer-panel__list">
          <div
              v-for="(item,key) in station_Techonlogy"
              v-if="temp.technology.indexOf(item.id)!=-1"
              :key="key"
              class="el-card is-hover-shadow"
              style="margin: 5px"
          >
            <div style="display: flex;align-items: center;padding: 2px 5px;">
              <p style="flex: 1;margin-left: 16px;padding:0px 8px">
                {{ item.technology_name }}
              </p>
              <div style="margin-left: 16px">
<!--                <el-popconfirm-->
<!--                    title="确定删除吗？"-->
<!--                    @confirm="delListVal(item.id)"-->
<!--                >-->
<!--                  <el-button slot="reference" circle icon="el-icon-delete" />-->
<!--                </el-popconfirm>-->
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
  <el-divider content-position="left">扩展信息</el-divider>
  <el-row :gutter="24">

    <el-col v-for="(item,kk) in temp.attrinfo" :key="kk" :span="item.inc_type=='3'?24:12">
      <el-form-item :label="item.name">
        <el-input :disabled="true"
            v-if="item.inc_type!='2'"
            v-model="item.attr_val"
            :type="item.inc_type=='3'?'textarea':'text'"
        />
        <el-select v-else v-model="item.attr_val" :disabled="true">
          <el-option v-for="(t,k) in item.list_val" :key="'a_'+k" :label="t.label" :value="t.label" />
        </el-select>
      </el-form-item>
    </el-col>

  </el-row>

  </el-form>
</div>
</template>
<script>
import {delArticle, fetchList, fetchPv} from "@/api/article";
import {buildCode, fetchDict} from "@/api/common";
import {getToken} from "@/utils/auth";
import {getTechonlogyCat} from "@/api/technology";
import {getcost, getDepartment, getDepartmentOne, getDepartmentTree, getlines} from "@/api/department";
import {getStationAttr, getStationAttrInfo, getStationGyxf, setStation} from "@/api/station";
import {parseTime} from "@/utils";
import {number} from "echarts/lib/export";

export default {
  name: "stationDetail",
  props:{
    station_id:{
      type:Number,
      default:"",
    }
  },
  data() {
    return {
      radio1: '文本',
      activeName: 'first',
      checked: true,
      tablesetvisible: false,
      tableKey: 0,
      list: null,
      attVisible: false,
      total: 0,
      listLoading: true,
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      },
      queryMap: {},
      showReviewer: false,
      temp: {
        id: '',
        dept_id: '',
        cost_id: '',
        line_id: '',
        dept_sn: '',
        line_sn: '',
        line_name: '',
        px:50,
        work_position: '',
        // station_code: '',
        station_number: '',
        station_name: '',
        station_name_en: '',
        supplier: '',
        cost_center: '',
        line_equipment_code: '',
        equipment_drawings: '',
        dev_type: '',
        active_version: '',
        email_send_status: '',
        technology_type: '',
        technology: [],
        dev_brand: '',
        del_flag: '',
        add_user_id: '',
        add_time: '',
        attrinfo: [],
        mea_id: '',
        process_id: '',
        maintenance_id: '',
        spare_id: ''

      },
      fileds: {
        dept_id: { filed: 'dept_id', title: '部门', is_show: '1' },
        cost_id: { filed: 'cost_id', title: '价值流', is_show: '1' },
        line_id: { filed: 'line_id', title: '产线', is_show: '1' },
        work_position: { filed: 'work_position', title: '工作位号', is_show: '1' },
        station_number: { filed: 'station_number', title: '站号', is_show: '1' },
        station_name: { filed: 'station_name', title: '设备名称', is_show: '1' },
        // station_name_en: {filed: 'station_name_en', title: '设备英文名', is_show: '1'},
        supplier: { filed: 'supplier', title: '供应商', is_show: '1' },
        cost_center: { filed: 'cost_center', title: '成本中心', is_show: '1' },
        // line_equipment_code: {filed: 'line_equipment_code', title: '生产线设备代码', is_show: '1'},
        // equipment_drawings: {filed: 'equipment_drawings', title: '设备图纸名称', is_show: '1'},
        dev_type: { filed: 'dev_type', title: '设备类型', is_show: '1' }
        // active_version: {filed: 'active_version', title: '当前版本', is_show: '1'},
        // technology_type: {filed: 'technology_type', title: '工艺类型', is_show: '1'},
        // technology: {filed: 'technology', title: '工艺', is_show: '1'},
        // dev_brand: {filed: 'dev_brand', title: '设备品牌', is_show: '1'}
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        dept_id: [{ required: true, message: '产线不能为空', trigger: 'change' }],
        //      station_code: [{required: true, message: '工作位号不能为空', trigger: 'change'}],
        station_number: [{ required: true, message: '站号不能为空', trigger: 'change' }],
        station_name: [{ required: true, message: '设备名称不能为空', trigger: 'change' }],
        station_name_en: [{ required: true, message: '设备英文名不能为空', trigger: 'change' }],
        // supplier: [{required: true, message: '供应商不能为空', trigger: 'change'}],
        // cost_center: [{required: true, message: '成本中心不能为空', trigger: 'change'}],
        line_equipment_code: [{ required: true, message: '生产线设备代码不能为空', trigger: 'change' }],
        // equipment_drawings: [{required: true, message: '设备图纸名称不能为空', trigger: 'change'}],
        dev_type: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
        // active_version: [{required: true, message: '当前版本不能为空', trigger: 'change'}],
        technology_type: [{ required: true, message: '工艺类型不能为空', trigger: 'change' }],
        // technology: [{required: true, message: '工艺不能为空', trigger: 'change'}],
        // dev_brand: [{required: true, message: '设备品牌不能为空', trigger: 'change'}],
        mea_id: [{ required: true, message: '请选择 mea 模板', trigger: 'change' }],
        process_id: [{ required: true, message: '请选择 process 模板', trigger: 'change' }],
        maintenance_id: [{ required: true, message: '请选择 maintenances 模板', trigger: 'change' }],
        spare_id: [{ required: true, message: '请选择 spare 模板', trigger: 'change' }]
      },

      mea_list: [],
      process_list: [],
      maintenance_list: [],
      spare_list: [],
      downloadLoading: false,
      departmentTree: [],
      dev_type_option: [],
      technology_type_option: [],
      station_attr: [],
      station_Techonlogy: [],
      lines: [],
      querylines: [],
      costs: [],
      querycosts: [],
      depts: [],
      supplierList: [],
      upheaders: {},
      updata: {},
      showup: false,
      types: [],
      loading:false
    }
  },
  watch: {
    'temp.dept_id': {
      async handler(newval, oldval) {
        if (oldval && newval != oldval) {
          console.log('旧值', oldval)
          this.temp.cost_id = ''
          this.temp.line_id = ''

        }

        if (newval) {
          const tempCosts = await getcost(newval)
          console.log(tempCosts)
          this.costs = tempCosts.data.items
          getDepartmentOne(newval).then((res) => {
            console.log('新部门值', res)
            this.temp.dept_sn = res.data.dept_sn
          })
          console.log('当前选选中的产线', this.temp.line_id)
        }
      }
    },
    'temp.line_id': {
      async handler(newval, oldval) {
        getDepartmentOne(newval).then((res) => {
          console.log('新部门值', res)
          this.temp.line_sn = res.data.dept_sn
        })
      }
    },
    'listQuery.dept_id': {
      async handler(newval, oldval) {
        if (oldval && newval != oldval) {
          console.log('旧值', oldval)
          this.listQuery.cost_id = ''
          this.listQuery.line_id = ''
        }

        if (newval) {
          const tempCosts = await getcost(newval)
          this.querycosts = tempCosts.data.items
        }
      }
    },
    'temp.cost_id': {
      async handler(newval, oldval) {
        if (oldval && newval != oldval) {
          console.log('有旧值')
          this.temp.line_id = ''
        }
        if (newval) {
          const tempCosts = await getlines(newval)
         // this.lines = tempCosts.data.items
          console.log('当前选选中的产线', this.temp.line_id)
        }
      }
    },
    'listQuery.cost_id': {
      async handler(newval, oldval) {
        if (oldval && newval != oldval) {
          console.log('旧值', oldval)
          this.listQuery.line_id = ''
        }

        if (newval) {
          const tempCosts = await getlines(newval)
          this.querylines = tempCosts.data.items
        }
      }
    },

    'temp.technology_type': {
      async handler(newval) {
        if (newval) {
          this.changeGy(newval)
        }
      }
    }

  },
  mounted() {
    this.getOption()
  },
  methods: {
    openStation(station){
      this.loading=true;
      console.log("传过来的",station)
      // this.setTplOption()
      this.getOption()
      setTimeout(()=>{
        this.handleUpdate(station)
      },500)

    },
    async setTplOption() {
      this.mea_list = await this.getTpl('MAE Info')
      console.log('mea_list的集合', this.mea_list)
      this.process_list = await this.getTpl('Process')
      this.maintenance_list = await this.getTpl('Maintenance')
      this.spare_list = await this.getTpl('Spare parts')
    },
    async getTpl(inc_type) {
      var query = {
        page_no: 1,
        limit: 2000,
        sort: 'id desc',
        where: {
          and: [{ field: 'inc_type', operator: '=', value: inc_type }, { field: 'is_public', operator: '=', value: '0' }]
        }
      }
      const res = await fetchList(query, 'sl_doc_template')
      console.log(inc_type, res.data.items)

      return res.data.items
    },

    handleClick() {

    },
    checkCode() {
      if (!this.temp.dept_sn) {
        this.$message.error('请先选择部门')
        return
      }
      if (!this.temp.cost_center) {
        this.$message.error('请输入成本中心')
        return
      }
      if (!this.temp.line_sn) {
        this.$message.error('请先选择产线')
        return
      }
      if (!this.temp.station_number) {
        this.$message.error('请输入站号')
        return
      }
      if (!this.temp.work_position) {
        this.$message.error('请输入工作位号')
        return
      }
      if (!this.temp.supplier) {
        this.$message.error('请输入供应商代号')
        return
      }

      const data = {
        dept: this.temp.dept_sn,
        cost: this.temp.cost_center,
        line: this.temp.line_sn,
        station_number: this.temp.station_number,
        work_position: this.temp.work_position,
        supplier_no: this.temp.supplier
      }

      buildCode(data).then((res) => {
        console.log('数据', res)
        this.$message.success('获取代码成功')
        this.temp.line_equipment_code = res.data
      })
    },
    handleSuccess(res1) {
      this.$message.info(res1.msg)
    },
    importExcel(item) {
      this.upheaders = {
        AccessToken: getToken()
      }

      this.updata = {
        // doc_id: item.id,
        // station_id: this.station_id
      }
      this.$refs.uploadRef.$refs['upload-inner'].$refs.input.click()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    changeAttr(index, val) {
      console.log('原属性', this.temp.attrinfo)
      if (val) {
        const temp = this.temp.attrinfo.filter((item) => {
          return item.attr_id == this.station_attr[index].attr_id
        })
        if (temp.length == 0) {
          this.temp.attrinfo.push(this.station_attr[index])
        }
      } else {
        this.temp.attrinfo = _.cloneDeep(this.temp.attrinfo.filter(item => {
          return item.attr_id !== this.station_attr[index].attr_id
        }))
      }
      console.log('属性', this.temp.attrinfo)
    },
    changeSubGy(index, val) {
      var has = this.temp.technology.indexOf(this.station_Techonlogy[index].id) == -1
      if (val) {
        if (has) {
          if (!this.temp.technology) {
            this.temp.technology = []
          }
          this.temp.technology.push(this.station_Techonlogy[index].id)
        }
      } else {
        if (!has) {
          this.delListVal(this.station_Techonlogy[index].id)
        }
      }
      console.log(index, val)
    },
    changeGy(val) {
      this.station_Techonlogy = []
      this.getGyxf(val)
    },
    getGyxf(parent_id) {
      getTechonlogyCat(parent_id).then((res) => {
        this.station_Techonlogy = res.data.items
      })
    },
    attClose() {

    },
    delListVal(id) {
      this.temp.technology = _.cloneDeep(this.temp.technology.filter(item => {
        return item != id
      }))
    },
    addListVal() {
      this.attVisible = true
    },
    emptyListVal() {
      this.temp.technology = []
    },
    getOption() {
      getDepartmentTree().then((res) => {
        if (res.data) {
          this.departmentTree = res.data
        }
      })
      fetchDict('dev_type').then((res) => {
        if (res.data.items) {
          this.dev_type_option = res.data.items
        }
      })
      fetchDict('供应商').then((res) => {
        if (res.data.items) {
          this.supplierList = res.data.items
        }
      })
      getStationAttr().then((res) => {
        if (!res.data.items) {
          res.data.items = []
        }
        console.log('公有属性', res)
        res.data.items.forEach((item) => {
          if (item.inc_type == '2') {
            if (item.list_val) {
              item.list_val = JSON.parse(item.list_val)
            } else {
              item.list_val = []
            }
          }
          item['attr_id'] = item['id']
          item['attr_val'] = ''
        })
        this.station_attr = res.data.items
        this.temp.attrinfo = res.data.items
      })
      getTechonlogyCat().then((option) => {
        if (!option.data.items) {
          option.data.items = []
        }
        option.data.items.unshift({
          id: '', technology_name: '无', parent_id: '0'
        })
        this.technology_type_option = option.data.items.filter(obj => obj.parent_id === '0')
        console.log('工艺类型', this.technology_type_option)
      })
      getDepartment().then((res) => {
        console.log('部门', res.data.items)
        this.depts = res.data.items
      })
    },
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery, 'sl_view_station').then(response => {
        if (response.data && response.data.items) {
          this.list = response.data.items
          this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    handleFilterReset() {
      this.listQuery = {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      }
      this.getList()
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)

      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          console.log('查询', listkeys[i], isNaN(listkeys[i]))
          let operator = '='
          let value = this.listQuery[listkeys[i]]
          if (!this.queryMap[listkeys[i]]) {
            if (isNaN(listkeys[i])) {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          } else {
            if (this.queryMap[listkeys[i]] == 'like') {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          }
        }
      }
      this.list = []
      this.listQuery['where'] = queryParma
      this.getList()
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        dept_id: '',
        cost_id: '',
        line_id: '',
        //  station_code: '',
        station_number: '',
        station_name: '',
        station_name_en: '',
        supplier: '',
        cost_center: '',
        line_equipment_code: '',
        equipment_drawings: '',
        dev_type: '',
        px:50,
        active_version: '',
        email_send_status: '',
        technology_type: '',
        technology: [],
        dev_brand: '',
        del_flag: '',
        add_user_id: '',
        add_time: '',
        attrinfo: [],
        mea_id: '',
        process_id: '',
        maintenance_id: '',
        spare_id: ''
      }
    },
    handleCreate() {
      console.log('创建时的属性值', this.temp.attrinfo)
      this.resetTemp()
      this.getOption()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const attr_data = this.temp.attrinfo
          console.log('工艺data', this.temp.technology)
          const technology_data = this.temp.technology
          console.log(technology_data)
          const data = {
            station_data: _.cloneDeep(this.temp),
            attr_data: attr_data,
            action: 1,
            technology_data: technology_data
          }
          data.station_data.technology = ''
          setStation(data).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          })
          this.list = []
          this.getList()
        } else {
          this.$message.error('请检查所有输入项')
        }
      })
    },
    async handleCopy(row) {
      this.temp = Object.assign({}, row) // copy obj
      // 还原工艺细分
      getStationGyxf(this.temp.id).then((res) => {
        console.log('工艺细分', res)
        if (res.data.items) {
          this.temp.technology = res.data.items.map((item) => {
            return item.technology_id
          })
        }

        // this.temp.technology=res.data.items
      })

      const attr = _.cloneDeep(this.station_attr)
      this.temp.attrinfo = attr
      // 还原扩展属性
      getStationAttrInfo(this.temp.id).then((res) => {
        console.log('基本属性', attr)
        if (res.data.items) {
          attr.forEach((item) => {
            var has = res.data.items.filter(it => it.attr_id == item.attr_id)
            if (has) {
              item.attr_val = has.attr_val
            }
          })
        }

        this.temp.attrinfo = attr
      })

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.id = ''

    },
    async handleUpdate(row) {
      this.temp = Object.assign(this.temp, row) // copy obj
      // 还原工艺细分
      getStationGyxf(this.temp.id).then((res) => {
        console.log('工艺细分', res)
        if (res.data.items) {
          this.temp.technology = res.data.items.map((item) => {
            return item.technology_id
          })
        }
        // this.temp.technology=res.data.items
      })

      const attr = _.cloneDeep(this.station_attr)
      this.temp.attrinfo = attr
      // 还原扩展属性
      getStationAttrInfo(this.temp.id).then((res) => {
        if (res.data.items) {
          attr.forEach((item) => {
            var has = res.data.items.filter(it => it.attr_id == item.attr_id)
            console.log('找到没', has)
            if (has && has.length > 0) {
              item.attr_val = has[0].attr_val
              console.log('修改' + item.attr_val)
            }
          })
        }
        console.log('修改后的attr', attr)
        this.temp.attrinfo = attr
      })

      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      this.loading=false;

    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const attr_data = this.temp.attrinfo
          console.log('data', this.temp.technology)
          const technology_data = this.temp.technology
          console.log(technology_data)
          const data = {
            station_data: _.cloneDeep(this.temp),
            attr_data: attr_data,
            action: 0,
            technology_data: technology_data
          }
          data.station_data.technology = ''
          setStation(data).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          })
          this.list = []
          this.getList()
        } else {
          this.$message.error('请检查所有输入项')
        }
      })
    },
    handleDeleteAll() {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      this.$confirm('你确定删除这' + this.multipleSelection.length + '条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(this.multipleSelection.map(item=>item.id))
      })
    },
    handleDelete(ids) {
      delArticle({ id: ids.join(',') }, 'sl_station').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>



<style scoped>

</style>
